package handle

import (
	"auth/model"
	"fmt"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
)

func RegistHandle(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	result := checkRegistParam(r.Form)
	if result != nil {
		SendResp(result, w)
		return
	}

	result = NewResult()
	client, err := model.SSDBPool.NewClient()
	if err != nil {
		fmt.Println(err.Error())

		result.Result = SystemError
		result.Message = ErrMessage[SystemError]
		SendResp(result, w)
		return
	}
	defer client.Close()

	username := r.Form.Get("username")
	channel := r.Form.Get("channel")
	//regist or not
	exist, err := model.AccountExist(client, username, channel)
	if err != nil {
		result.Result = SystemError
		result.Message = ErrMessage[SystemError]
		SendResp(result, w)
		return
	}

	if exist {
		result.Result = UserExist
		result.Message = ErrMessage[UserExist]
		SendResp(result, w)
		return
	}

	uid := model.NewUid(client)
	if uid <= 0 {
		result.Result = SystemError
		result.Message = ErrMessage[SystemError]
		SendResp(result, w)
		return
	}

	account := model.NewAccount()
	account.Uid = uid
	account.Username = username
	account.Channel = channel
	account.Passwd = r.Form.Get("passwd")
	account.Mobile = r.Form.Get("mobile")
	platform, _ := strconv.Atoi(r.Form.Get("platform"))
	account.Platform = int8(platform)

	err = model.Regist(client, account)
	if err != nil {
		result.Result = SystemError
		result.Message = ErrMessage[SystemError]
	}
	SendResp(result, w)
}

func checkRegistParam(form url.Values) *Result {
	err := NewResult()

	username := form.Get("username")
	if len(username) == 0 {
		err.Result = UsernameIsNULL
		err.Message = ErrMessage[UsernameIsNULL]
		return err
	}

	match, _ := regexp.MatchString(`^[0-9a-zA-Z_]+$`, username)
	if !match {
		err.Result = UsernameIsInvalid
		err.Message = ErrMessage[UsernameIsInvalid]
		return err
	}

	passwd := form.Get("passwd")
	len := len(passwd)
	if len == 0 {
		err.Result = PasswdIsNULL
		err.Message = ErrMessage[PasswdIsNULL]
		return err
	}

	if len > kPasswdMaxLen || len < kPasswdMinLen {
		err.Result = PasswdIsInvalid
		err.Message = ErrMessage[PasswdIsInvalid]
		return nil
	}

	confirm := form.Get("confirm")
	if confirm != passwd {
		err.Result = PasswdIsDiff
		err.Message = ErrMessage[PasswdIsDiff]
		return err
	}

	mobile := form.Get("mobile")
	matched, _ := regexp.MatchString(`^1[0-9]{10}$`, mobile)
	if !matched {
		err.Result = PhoneNoIsInvalid
		err.Message = ErrMessage[PhoneNoIsInvalid]
		return err
	}

	//TODO check whether the channel is valid

	//TODO check whether the platform is valid

	return nil
}
